package com.jiangjiang.eshop.pay.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.jiangjiang.eshop.order.service.OrderService;
import com.jiangjiang.eshop.pay.api.QueryPayStatusResponse;
import com.jiangjiang.eshop.pay.constant.PayTransactionStatus;
import com.jiangjiang.eshop.pay.dto.PayTransactionDTO;
import com.jiangjiang.eshop.pay.dto.PayTransactionQueryCondition;
import com.jiangjiang.eshop.pay.service.PayTransactionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author Jianghaowen
 * @Date 2021/9/30
 * @Description: TODO
 * @Version V1.0
 **/
@Slf4j
@RestController
@RequestMapping("/pay/api")
public class PayApiController {

    @Autowired
    private PayTransactionService payTransactionService;
    @Autowired
    private OrderService orderService;

    /**
     * 接收微信支付的状态
     *
     * @param response 支付响应
     * @return 处理结果
     */
    @PostMapping("/wax/pay/callback")
    public Boolean waxPayCallback(@RequestBody QueryPayStatusResponse response) {
        try {
            PayTransactionQueryCondition condition = PayTransactionQueryCondition.builder()
                    .orderNo(response.getOrderNo())
                    .build();

            List<PayTransactionDTO> payTransactionDTOList = payTransactionService.queryByCondition(condition);
            if (CollectionUtils.isEmpty(payTransactionDTOList)) {
                return false;
            }
            PayTransactionDTO payTransaction = payTransactionDTOList.get(0);
            payTransaction.setUserPayAccount(response.getUserPayAccount());
            payTransaction.setTransactionNumber(response.getTransactionNumber());
            payTransaction.setFinishPayTime(response.getFinishPayTime());
            payTransaction.setResponseCode(response.getResponseCode());
            payTransaction.setStatus(response.getPayTransactionStatus());
            payTransactionService.update(payTransaction);

            if (PayTransactionStatus.SUCCESS.equals(response.getPayTransactionStatus())) {
                orderService.informPayOrderSucceed(payTransaction.getOrderInfoId());
            }


        } catch (Exception e) {
            log.warn("PayApiController waxPayCallback error", e);
        }
        return false;
    }
}
